package com.study.ui.test.test_download

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import com.lbj.core.ext.setClickNoRepeat
import com.lbj.core.ext.toLog
import com.lbj.core.ext.toToast
import com.lbj.mvvm.ext.getVersionCode
import com.lbj.mvvm.update.AppUpdate
import com.lbj.mvvm.update.OkHttpNetManager
import com.lbj.mvvm.update.net.INetCallback
import com.lbj.mvvm.update.net.INetDownloadCallback
import com.study.R
import kotlinx.android.synthetic.main.activity_test_download.*
import java.io.File
import kotlin.text.toLong as toLong

class TestDownloadActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_download)

        AppUpdate.init(OkHttpNetManager())

        btnDownload.setClickNoRepeat {
            /**
            "title":"4.5.0更新啦！",
            "content":"1. 优化了阅读体验；\n2. 上线了 hyman 的课程；\n3. 修复了一些已知问题。",
            "url":"http://59.110.162.30/v450_imooc_updater.apk",
            "md5":"14480fc08932105d55b9217c6d2fb90b",
            "versionCode":"450"
             */
            AppUpdate.getManager()
                .get("http://59.110.162.30/app_updater_version.json", object : INetCallback {
                    override fun success(response: String) {
                        "更新接口成功".toLog()
                        val downloadBean = DownloadBean.parse(response)
                        if (downloadBean.url.isEmpty()) {
                            "下载链接有误".toToast()
                            return
                        }
                        // 检测是否需要版本更新
                        try {
                            val versionCode = downloadBean.versionCode.toLong()
                            // 只有服务器版本号大于本地版本号才会进行下载
                            if (versionCode <= this@TestDownloadActivity.getVersionCode()) {
                                "当前是最新版本".toToast()
                                return
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            "获取版本号有误".toToast()
                        }

                        // 版本更新 弹出Dialog
                        ApkUpdateDialog.show(this@TestDownloadActivity, downloadBean)
                    }

                    override fun failure(e: Throwable) {
                        "更新接口失败".toToast()
                    }
                }, AppUpdate.TAG_CANCEL)
        }
    }

    override fun onDestroy() {
        AppUpdate.getManager().cancel(AppUpdate.TAG_CANCEL)
        super.onDestroy()
    }
}